package com.itzyf.pokemondata.activity.gallery

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.AsyncTask
import android.os.Environment
import android.view.Menu
import android.view.MenuItem
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.gif.GifDrawable
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.itzyf.pokemondata.R
import com.itzyf.pokemondata.utils.FileUtil
import com.tydic.baselibrary.activity.BaseActivity
import com.tydic.baselibrary.contant.Constant
import kotlinx.android.synthetic.main.activity_gif.*
import java.io.File


class GifActivity : BaseActivity() {
    override fun handlerActivity() {
        setTitle(intent.getStringExtra("title"))
        showProgressDialog()
        Glide.with(this)
            .asGif()
            .listener(object : RequestListener< GifDrawable> {
                override fun onLoadFailed(
                    e: GlideException?,
                    model: Any?,
                    target: Target<GifDrawable>?,
                    isFirstResource: Boolean
                ): Boolean {
                    showToast("加载失败")
                    return false
                }

                override fun onResourceReady(
                    resource: GifDrawable?,
                    model: Any?,
                    target: Target<GifDrawable>?,
                    dataSource: DataSource?,
                    isFirstResource: Boolean
                ): Boolean {
                    dismissProgressDialog()
                    return false
                }

            })
            .load(intent.getStringExtra("image"))
            .into(ivGif)

    }

    override fun getContentViewId() = R.layout.activity_gif

    override fun getToolbarTitle() = "沙漠副本"
    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.save, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        if (item?.itemId == R.id.action_save) {
            if (hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                doSDCardPermission()
            } else {
                requestPermission(
                    Constant.WRITE_READ_EXTERNAL_CODE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
            }
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    override fun doSDCardPermission() {
        download(intent.getStringExtra("image"))
    }


    // 保存图片到手机
    private fun download(url: String) {

        object : AsyncTask<Void, Int, File>() {

            override fun doInBackground(vararg params: Void): File? {
                var file: File? = null
                try {
                    val future = Glide
                        .with(this@GifActivity)
                        .load(url)
                        .downloadOnly(
                            com.bumptech.glide.request.target.Target.SIZE_ORIGINAL,
                            com.bumptech.glide.request.target.Target.SIZE_ORIGINAL
                        )

                    file = future.get()

                    // 首先保存图片
                    val pictureFolder =
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).absoluteFile

                    val appDir = File(pictureFolder, "fuke")
                    if (!appDir.exists()) {
                        appDir.mkdirs()
                    }
                    val fileName = System.currentTimeMillis().toString() + ".gif"
                    val destFile = File(appDir, fileName)

                    FileUtil.CopyFile(file, destFile)

                    // 最后通知图库更新
                    sendBroadcast(
                        Intent(
                            Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                            Uri.fromFile(File(destFile.getPath()))
                        )
                    )


                } catch (e: Exception) {
                    e.printStackTrace()
                }

                return file
            }

            override fun onPostExecute(file: File) {
                showToast("保存成功")
            }

        }.execute()
    }

}